<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\OrdersModel;
use Illuminate\Support\Facades\DB;

class OrdersDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = OrdersModel::query();
        $query->when(checkIsHasField($params,'orders_id'),function ($query)use ($params){
            $query->where('orders_id',$params['orders_id']);
        });

        $query->when(checkIsHasField($params,'orders_code'),function ($query)use ($params){
            $query->where('orders_code',$params['orders_code']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'re_user_id'),function ($query)use ($params){
            $query->where('re_user_id',$params['re_user_id']);
        });
        return $query->orderByDesc('created_at');
    }
    public static function orders($params = []): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query($params)->paginate();
    }

    public static function orders_info($params = []): array
    {
        return self::builder_query($params)->first()->toArray();
    }


    /**
     * @desc 订单下单
     * @param array $params
     * @return void
     * @throws SysExceptions
     */
    public static function orders_create(array $params = [])
    {
        checkForData(['user_id','goods_id','address_id'],['用户不正确','请选择商品','请选择地址'],$params);
        $address_query = AddressDao::get_address_builder_query(['address_id'=>$params['address_id']]);
        if(!$address_query->exists()){
            self::error('地址不存在');
        }
        $address_info = $address_query->first()->toArray();
        $goods_query = GoodsDao::builder_query(['goods_id'=>$params['goods_id'],'show'=>1]);
        if(!$goods_query->exists()){
            self::error('请选择正确的商品');
        }
        //商品信息
        $goods_info = $goods_query->first()->toArray();
        //获取用户信息
        $user_query = UsersDao::builder_query(['user_id'=>$params['user_id']]);
        if(!$user_query->exists()){
            self::error('用户不存在');
        }
        //用户信息
        $user_info = $user_query->first()->toArray();
        if($user_info['money'] < $goods_info['goods_price']){
            self::error('金额不足!');
        }
        //创建订单
        $order_data = [
            'user_id'=>$params['user_id'],
            'status'=>1,
            'price'=>$goods_info['goods_price'],
            'orders_code'=>makeOrderNo(),
            'goods_id'=>$params['goods_id'],
            'address_id'=>$params['address_id'],
            'address_json'=>json_encode($address_info,JSON_UNESCAPED_UNICODE),
            'orders_json_data'=>json_encode($goods_info,JSON_UNESCAPED_UNICODE),
        ];
        //创建订单并且扣费
        DB::beginTransaction();
        try {
            self::builder_query()->create($order_data);
            BillsDao::moneysUpdate(-($order_data['price']),$order_data['user_id'],'购买商品扣费');
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function userUploadInfo(array $params)
    {
        //查询状态已经发货不允许修改
        checkForData(['orders_id','user_uplaod_info'],['请选择订单','请填写上传信息'],$params);
        $order_query = self::builder_query(['orders_id'=>$params['orders_id']]);
        if(!$order_query->exists()){
            self::error('订单不存在');
        }
        $orders_info = $order_query->first()->toArray();
        if($orders_info['status'] > 2){
            self::error('订单状态不正确!');
        }
        if(!$order_query->update([
            'user_uplaod_info' => json_encode($params['user_uplaod_info'], JSON_UNESCAPED_UNICODE),
            'status'=>2
        ])){
            self::error('订单修改失败!');
        }
    }

    /**
     * @desc 订单发货
     * @param array|null $params
     * @return void
     * @throws SysExceptions
     */
    public static function send_orders(array $params)
    {
        checkForData(['wuliu_num'],['请输入物流单号'],$params);
        $orders_query = self::builder_query(['orders_id'=>$params['orders_id']]);
        if(!$orders_query->exists()){
            self::error('订单不存在!');
        }
        $orders_info = $orders_query->first()->toArray();
        if($orders_info['status'] != 2){
            self::error('订单状态不正确!');
        }

        if (self::builder_query(['orders_id'=>self::deleteParamId($params,'orders_id')])->update(['wuliu_num'=>$params['wuliu_num'],'status'=>3]) === false){
            self::error('修改失败');
        }
    }

    public static function confirm(array $params)
    {
        //确认收货升级/返佣
        $orderQuery = self::builder_query([
            'orders_code'=>$params['orders_code']
        ]);
        //订单不存在
        if(!$orderQuery->exists()){
            self::error('订单不存在!');
        }
        //订单信息
        $orderInfo = $orderQuery->first()->toArray();
        //确认收货并且绑定
        DB::beginTransaction();
        try {
            //确认收货
            $orderQuery->update([
                'status'=>4,
                're_user_id'=>$params['re_user_id']
            ]);
            //进行升级或者返费
            self::changeLevel($orderInfo);
            //进行经营收费
            self::changeJinYingPrice($orderInfo);
            //不是指定的商品返费10%
            self::changeGoods($orderInfo);
            DB::commit();
        }catch (\Exception $exception){

        }
    }

    /**
     * @throws SysExceptions
     */
    private static function changeLevel(array $orderInfo)
    {
        $goodsInfo = json_decode($orderInfo['orders_json_data'],true);

        if($goodsInfo['is_buy_vip_level'] == 0){
            return;
        }
        $user_Info = UsersDao::builder_query([
            'user_id'=>$orderInfo['user_id']
        ])->first()->toArray();
        //客户不走这条线
        if($user_Info['vip_type'] == 2){
            return ;
        }
        //增加到用户信息
        UsersDao::builder_query([
            'user_id'=>$orderInfo['user_id']
        ])->increment('user_prices_level',$goodsInfo['goods_price']);
        $user_Info = UsersDao::builder_query([
            'user_id'=>$orderInfo['user_id']
        ])->first()->toArray();
        //大于9900升级运营中心并且向上级返费
        if($user_Info['user_prices_level'] < 9900){
            return;
        }
        //查询上级的下边有几个

        if($user_Info['vip_level'] < 1){
            $count = 0;
            //查询上级有几个
            if($user_Info['spread_id'] != 0){
                $count = UsersDao::builder_query([
                    'spread_id'=>$user_Info['spread_id'],
                ])->where('vip_level','>',0)->count();
                $count+=1;
                $priceUp = 3000;
                if($count >= 3){
                    $priceUp = 6000;
                }
                //给上级用户升级成为老板
                if($count >= 3){
                    UsersDao::builder_query([
                        'user_id'=>$user_Info['spread_id']
                    ])->where('vip_level','<',2)->update([
                        'vip_level'=>2
                    ]);

                }

                //给上级钱
                BillsDao::moneysUpdate($priceUp,$user_Info['spread_id'],'下级用户成为运营中心奖励');
                //找上级所在的第三节电，无限极查询翻找
                $spread_user_id = $user_Info['spread_id'];
                $sprea_index_uid = 0;
                while (true){
                    if($spread_user_id == 0){
                        break;
                    }
                    $spread_info = UsersDao::builder_query([
                        'user_id'=>$spread_user_id
                    ])->first()->toArray();
                    //处于第三届点
                    if($spread_info['user_spread_index'] == 3){
                        $sprea_index_uid = $spread_info['spread_id'];
                        break;
                    }
                    $spread_user_id = $spread_info['spread_id'];
                }
                //找到节节点
                if($sprea_index_uid != 0){
                    BillsDao::moneysUpdate(2000,$spread_info['spread_id'],'下级用户成为运营中心奖励(间接)');
                }
            }
            UsersDao::builder_query([
                'user_id'=>$user_Info['user_id']
            ])->update([
                'vip_level'=>1,
                'user_spread_index'=>$count
            ]);
        }
    }

    /**
     * @throws SysExceptions
     */
    private static function changeJinYingPrice(array $orderInfo)
    {
        $goodsInfo = json_decode($orderInfo['orders_json_data'],true);

        if($goodsInfo['is_buy_vip_level'] == 0){
            return;
        }



        $user_Info = UsersDao::builder_query([
            'user_id'=>$orderInfo['user_id']
        ])->first()->toArray();
        if($user_Info['vip_type'] == 1){
            return ;
        }
        $user_spraed_id = $user_Info['spread_id'];
        //判断购买人是不是经营中心,不是的话查找上级
        if($user_Info['vip_level'] == 0){
            $user_Info = UsersDao::builder_query([
                'user_id'=>$user_Info['spread_id']
            ])->first()->toArray();
            $user_spraed_id = $user_Info['user_id'];
        }

        //代理不走这条线

        if($user_Info['vip_level'] == 0){
            return;
        }
        //查过30个不走这个
        if($user_Info['vip_type_2_nums'] == 30){
            return;
        }
        //给30%提成
        $moneyBeChange = $goodsInfo['goods_price'] *0.3;

        BillsDao::moneysUpdate($moneyBeChange,$user_spraed_id,'经营收入');
        UsersDao::builder_query(['user_id'=>$user_spraed_id])->increment('vip_type_2_nums',1);
    }

    private static function changeGoods(array $orderInfo)
    {
        $goodsInfo = json_decode($orderInfo['orders_json_data'],true);

        if($goodsInfo['is_buy_vip_level'] == 1){
            return;
        }
        $user_Info = UsersDao::builder_query([
            'user_id'=>$orderInfo['user_id']
        ])->first()->toArray();
        //给谁处于第三位置的老板返费10%
        $spread_user_id = $user_Info['spread_id'];
        $sprea_index_uid = 0;
        while (true){
            if($spread_user_id == 0){
                break;
            }
            $spread_info = UsersDao::builder_query([
                'user_id'=>$spread_user_id
            ])->first()->toArray();
            //处于第三届点
            if($spread_info['user_spread_index'] == 3){
                $sprea_index_uid = $spread_info['spread_id'];
                break;
            }
            $spread_user_id = $spread_info['spread_id'];
        }
        //找到节节点
        if($sprea_index_uid != 0){
            BillsDao::moneysUpdate($goodsInfo['goods_price']*0.1,$spread_info['spread_id'],'10%消费奖励');
        }
    }

    public static function ordersRevi(array $params)
    {
        return self::builder_query($params)->get()->toArray();
    }
}
